package vn.co.thn.android.videohot.fragment;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import vn.co.thn.android.serviceconnect.callback.RequestCallBack;
import vn.co.thn.android.videohot.R;
import vn.co.thn.android.videohot.VHApp;
import vn.co.thn.android.videohot.VHUrlApi;
import vn.co.thn.android.videohot.adapter.VHCategoryListAdapter;
import vn.co.thn.android.videohot.common.VHCommonFragment;
import vn.co.thn.android.videohot.data.VHCategoryItemData;
import vn.co.thn.android.videohot.json.VHJsonCategoryList;

public class VHCategoryFragment extends VHCommonFragment implements OnItemClickListener {
	private ListView mCategory_List;
	private VHCategoryListAdapter adapter;

	public static VHCategoryFragment getInstance() {
		VHCategoryFragment fragment = new VHCategoryFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.vh_common_list_fragment, container, false);
		mCategory_List = (ListView) view.findViewById(R.id.lst);
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		mCategory_List.setOnItemClickListener(this);
		if (VHApp.getPreference().getCategoryList() != null) {
			adapter = new VHCategoryListAdapter(getActivity(), VHApp.getPreference().getCategoryList().getCategory_list());
			mCategory_List.setAdapter(adapter);
		} else {
			mRequestService.setUrl(VHUrlApi.Api_Category_List);
			mRequestService.setRequestCallBack(new RequestCallBack<VHJsonCategoryList>() {

				@Override
				public void onResult(VHJsonCategoryList data, boolean isUpdate) {
					// TODO Auto-generated method stub
					adapter = new VHCategoryListAdapter(getActivity(), VHApp.getPreference().getCategoryList().getCategory_list());
					mCategory_List.setAdapter(adapter);
				}

				@Override
				public void onResult(ArrayList<VHJsonCategoryList> data, boolean isUpdate) {
					// TODO Auto-generated method stub

				}
			});
			mRequestService.PostAndCache();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		VHCategoryItemData category = (VHCategoryItemData) mCategory_List.getItemAtPosition(position);
		// TODO Auto-generated method stub
		replaceFragmentNoBackStackWithAnimation(VHVideoCategoryFragment.newInstance(category.getKey() + ""));
	}
}
